package com.freejava.test_websocket.controller;

import com.freejava.test_websocket.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
@RequestMapping("/v1")
public class ChatController {

    @Autowired
    ChatService chatService;

    // 登录页面
    @GetMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("/login");
    }

    @GetMapping("/chat")
    public ModelAndView index(String username, String password, HttpServletRequest request) throws UnknownHostException {
        // 编写service去检测用户名和密码是否有效
        String errorMsg = "";
        System.out.println(username);
        if (!chatService.isValidUserName(username)) {
            errorMsg = "名称必须是长度2-20之内！";
        }

        if (!chatService.isValidPassword(password)) {
            errorMsg = "密码的长度必须是6到12位！";
        }

        if (errorMsg == "") {
            ModelAndView modelAndView = new ModelAndView("/chat");
            modelAndView.addObject("username", username);
            modelAndView.addObject("webSocketUrl", "ws://" + InetAddress.getLocalHost().getHostAddress() + ":" + request.getServerPort() + request.getContextPath() + "/chat");
            return modelAndView;
        } else {
            // 返回错误页面
            ModelAndView modelAndView = new ModelAndView("/error");
            modelAndView.addObject("errorMsg", errorMsg);
            return modelAndView;
        }
    }

}
